package com.campus.wall.adapter;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.campus.wall.R;
import com.campus.wall.response.MessageResponse;

import java.util.List;

public class FriendAdapter extends RecyclerView.Adapter<FriendAdapter.MyHolder>   implements View.OnClickListener {

    private List<MessageResponse> mList;//数据源
    private Activity activity;
    private LayoutInflater mInflater;

    public FriendAdapter(List<MessageResponse> list, Activity activity) {
        mList = list;
        this.activity=activity;
        this.mInflater = LayoutInflater.from(activity);
    }
    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view =mInflater
                .inflate(R.layout.layout_friend_item, parent, false);
        MyHolder holder = new MyHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyHolder holder, int position) {
        MessageResponse messageResponse= mList.get(position);
        holder.name.setText(messageResponse.getName());
        holder.liner.setTag(position);
        int img =activity.getResources().getIdentifier(activity.getPackageName()+messageResponse.getImage(),
                null,null);
        holder.photo.setImageResource(img);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    @Override
    public void onClick(View view) {
        int position = (int) view.getTag();      //getTag()获取数据
        if (mOnItemClickListener != null) {
            mOnItemClickListener.onItemClick(view, position);
        }
    }

    class MyHolder extends RecyclerView.ViewHolder {

        TextView name;
        ImageView photo;
        LinearLayout liner;
        public MyHolder(@NonNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.name);
            photo = itemView.findViewById(R.id.photo);
            liner=itemView.findViewById(R.id.liner);
            liner.setOnClickListener(FriendAdapter.this::onClick);
        }
    }

    //自定义一个回调接口来实现Click和LongClick事件
    public interface OnItemClickListener {
        void onItemClick(View v, int position);
    }
    private OnItemClickListener mOnItemClickListener;

    //定义方法并传给外面的使用者
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

}
